package com.xch.sboot.service.common;

import com.xch.sboot.common.exception.BusinessException;
import com.xch.sboot.common.util.RSAUtil;
import com.xch.sboot.config.login.LoginProperties;
import com.xch.sboot.service.common.dto.KeyPairDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.KeyPair;
import java.util.Base64;

/**
 * @author xch
 * 2022/12/14 15:49
 */
@Service
public class CommonService {

    @Resource
    private RedisDataService redisDataService;

    @Resource
    private LoginProperties loginProperties;

    public String getPublicKey(String requestId) {
        if (StringUtils.isEmpty(requestId)) {
            return loginProperties.getPublicKey();
        }
        try {
            if (redisDataService.hasKey(requestId)) {
                KeyPairDTO keyPair = (KeyPairDTO) redisDataService.getRedisObject(requestId);
                return keyPair.getPublicKey();
            }
            KeyPair keyPair = RSAUtil.getKeyPair();
            String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
            String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
            KeyPairDTO keyPairDTO = new KeyPairDTO();
            keyPairDTO.setPublicKey(publicKey);
            keyPairDTO.setPrivateKey(privateKey);
            redisDataService.setRedisData(requestId, keyPairDTO, 20);
            return Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("获取公钥失败！");
        }
    }


    public String getPrivateKey(String requestId) {
        if (StringUtils.isEmpty(requestId)) {
            return loginProperties.getPrivateKey();
        }
        try {
            if (!redisDataService.hasKey(requestId)) {
                throw new BusinessException("请重新尝试登录！");
            }
            KeyPairDTO keyPair = (KeyPairDTO) redisDataService.getRedisObject(requestId);
            //获取之后就删除
            redisDataService.delete(requestId);
            return keyPair.getPrivateKey();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("请重新尝试登录！");
        }
    }
}
